package com.gvtv.main.execute;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;

import com.gvtv.main.util.AppTools;

public class JobWorkerMapping {

	private static final Logger logger = Logger.getLogger(JobWorkerMapping.class);
	
	private static String JOB_MAPPING = "/conf/job-mapping.xml";
	private static JobWorkerMapping instance;
	private static byte[] lock = new byte[0];
	private Map<String, String> mapping;
	
	public JobWorkerMapping(){
		mapping = new ConcurrentHashMap<String, String>();
		load();
	}
	
	public static JobWorkerMapping getInstance(){
		if(instance!=null){
			return instance;
		}else {
			synchronized(lock){
				if(instance!=null){
					return instance;
				}else {
					instance = new JobWorkerMapping();
					return instance;
				}
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	private void load(){
		try {
			XMLConfiguration conf = new XMLConfiguration(AppTools.getBaseDir()+JOB_MAPPING);
			List list = conf.getList("mapping.type");
			for(int i=0,len=list.size();i<len;i++){
				String type = conf.getString("mapping("+i+").type");
				String jobClass = conf.getString("mapping("+i+").job-class");
				this.addMapping(type, jobClass);
			}
		} catch (ConfigurationException e) {
			logger.error(e);
		}
	}
	
	public void addMapping(String type, String jobClass){
		this.mapping.put(type.toUpperCase(), jobClass);
	}
	
	public String getMapping(String type){
		return mapping.get(type.toUpperCase());
	}
	
	public static void main(String[] args){
		getInstance();
	}
}
